package com.cxb.java;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @Classname SharedNOReentrantLock
 * @Date 2023/4/1 10:39
 * @Created by Administrator
 * @Description TODO
 */
public class SharedNOReentrantLock implements Runnable {
    private InterProcessSemaphoreMutex lock;//不可重入锁
    private String lockPAth = "/lock/shareLock";
    private int i;
    private String clientName;
    //zookeeper集群地址
    public static final String ZOOKEEPER_STRING = "127.0.0.1:2181";

    public SharedNOReentrantLock(CuratorFramework client, String clientName) {
        lock = new InterProcessSemaphoreMutex(client, lockPAth);
        this.clientName = clientName;
    }

    public void run() {
        try {
            Thread.sleep((new java.util.Random().nextInt(2000)));
            lock.acquire();  //增加第一把锁
            if (lock.isAcquiredInThisProcess()) {
                System.out.println(clientName + " 获得锁");
                i++;
            }
            lock.acquire();  //增加第二把锁这个锁相当于不起作用
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
//                lock.release();
                System.out.println(clientName + "释放第一把锁");
                lock.release();
                System.out.println(clientName + "释放第二把锁");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        CuratorFramework client = CuratorFrameworkFactory.newClient(ZOOKEEPER_STRING, new ExponentialBackoffRetry(1000, 3));
        client.start();
        for (int i = 0; i < 100; i++) {
            SharedNOReentrantLock sharedNOReentrantLock = new SharedNOReentrantLock(client, "第" + i + "个客户端：");
            Thread thread = new Thread(sharedNOReentrantLock);
            thread.start();
        }
    }

}

